home *** CD-ROM | disk | FTP | other *** search
- Path: grimsel.zurich.ibm.com!usenet
- From: wgk@zurich.ibm.com (Keith Whittingham)
- Newsgroups: comp.lang.c++
- Subject: Re: Can I do it recursively?
- Date: 3 Apr 1996 09:05:26 GMT
- Organization: IBM Research, ZRH
- Message-ID: <4jtf0m$30s@grimsel.zurich.ibm.com>
- References: <4jrcqj$3s1@nuscc.nus.sg>
- Reply-To: wgk@zurich.ibm.com
- NNTP-Posting-Host: pine.zurich.ibm.com
- X-Newsreader: IBM NewsReader/2 v1.00
-
- In <4jrcqj$3s1@nuscc.nus.sg>, eng50636@leonis.nus.sg (Sun Jian) writes:
- > I am doing a program of a famous problem(forget the name, sorry). It is
- >about how a horse can travel through the whole 8x8 chess board,without
- >repeating any position that has been travelled(may seem to easy for
- >experts---I am only a beginner). I want to do it by recursion. But it
- >seems quite impossible since the run-time is too long.
-
-
- I have not heard of this problem before but I guess without thinking too
- long that recursion should work OK. You need an 8 x 8 array to keep
- track of where you've been, and a depth counter to know when you've
- visited 64 squares. Stack shouldn't be too much of a problem providing
- you keep stack variables to a minimum - there needs to be 64 recursive
- calls so it there are 20 bytes of return, address, arguments and auto
- variables you still only use 1.2K of stack.
-
- Recursion is probably the best way of handling the problem without
- writing a very complex algorithm. The code should look something like
- this...
-
- char BeenThere[8][8];
-
- int IsValid(int Coord)
- {
- return ((Coord >= 0) && (Coord < 8);
- }
-
-
- int Visit(int x,int y)
- {
- int Result = 0;
- static int Depth;
-
- if(Isvalid(x) && Isvalid(y))
- {
- if(!BeenThere[x][y])
- {
- BeenThere[x][y] = 1;
- if(++Depth == 8*8)
- {
- Result = 1;
- }
- else
- {
- Result = Visit(x+1, y+2);
- if(!Result) Result = Visit(x+2, y+1);
- if(!Result) Result = Visit(x+2, y-1);
- if(!Result) Result = Visit(x+1, y-2);
- /* etc... */
- }
- if(!Result)
- {
- BeenTher[x][y] = 0;
- Depth--;
- }
- }
- }
-
- return Result;
- }
-
- main()
- {
- puts(Visit(0, 0) ? "0,0 is OK" : "0,0 is not OK");
-
- return 0;
- }
-
- As you can see the starting position may effect the result? You may want to
- loop through all possible positions in the main.
-
- The above code can, I'm sure, be beautified but the idea should work I think.
-
- If the algorithm is slow then it could be optimised (I think) by checking
- for isolated squares at the top of the Visit() function - "If there are
- squares that can't be reached then there's no point in carrying on down
- this path". This would probably be more suitable to chess boards bigger
- than 8 x 8.
-
-
- Hope that helps...
-
- Keith
-
-
-
-